package com.GameSpace.CoreAssets;

import com.GameSpace.SameGame.R;

import android.content.Context;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.GridView;

public class ChoiceView extends GridView implements OnClickListener{

	public static final int DefaultSpacing = 10;
	public static final ChoiceViewStyle DefaultStyle = ChoiceViewStyle.Square;
	private View[] buttons;
	private int columnCount;
	public ChoiceListener listener;
	private int rowCount;
	private int spacing = DefaultSpacing;
	private ChoiceViewStyle style = DefaultStyle; 
	
	public ChoiceView(Context context, View[] buttons) {
		this(context, buttons, DefaultStyle, DefaultSpacing);
	}

	public ChoiceView(Context context, View[] buttons, ChoiceViewStyle style) {
		this(context, buttons, style, DefaultSpacing);
	}

	public ChoiceView(Context context, View[] buttons, ChoiceViewStyle style, int spacing) {
		super(context);
		this.style = style;
		this.spacing = spacing;
		this.buttons = buttons;
		this.setStretchMode(STRETCH_COLUMN_WIDTH);
		calculateRowAndColumnCount();
		setDimensions();
		setButtonListeners();
		this.setAdapter(new ButtonAdapter(buttons));
	}

	private void calculateRowAndColumnCount(){
		switch (style) {
		case Horizontal:
			rowCount = 1;
			columnCount = buttons.length;
			break;
		case Vertical:
			rowCount = buttons.length;
			columnCount = 1;
			break;
		case Square:
			default:
			rowCount = (int) Math.ceil(Math.sqrt(buttons.length));
			columnCount = (int) Math.ceil(((double)buttons.length)/rowCount);
			break;
		}
	}

	public View[] getButtons() {
		return buttons;
	}

	public int getSpacing() {
		return spacing;
	}

	public void onClick(View v) {
		if(listener == null){
			return;
		}
		for(int i = 0; i < buttons.length; i++){
			if(buttons[i] == v){
				listener.choiceSelected(i);
				break;
			}
		}
	}
	
	public void playAnimation(){
		Animation aLeft = AnimationUtils.loadAnimation(getContext(), R.anim.choicestartfromleft);
		Animation aRight = AnimationUtils.loadAnimation(getContext(), R.anim.choicestartfromright);
		for(int i = 0; i < buttons.length;i++){
			boolean toLeft;
			switch (style) {
			case Horizontal:
				toLeft = i < buttons.length / 2;
				break;
			case Vertical:
			case Square:
			default:
				toLeft = i / columnCount % 2 == 0;
				break;
			}
			if(toLeft){
				buttons[i].setAnimation(aLeft);
			}else {
				buttons[i].setAnimation(aRight);
			}
			
		}
	}

	private void setButtonListeners() {
		for(View button : buttons){
			button.setOnClickListener(this);
		}
	}
	
	private void setDimensions() {
		setNumColumns(columnCount);
		setVerticalSpacing(spacing);
		setHorizontalSpacing(spacing);
		setGravity(Gravity.CENTER);
	}

}
